import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.regex.Matcher;


public class GetSkillImages {

    final static File WORK_DIR = new File("C:/tmp/x/skillimgs");
    final static File DOWNLOAD_DIR = new File(WORK_DIR,"auto");
    final static File SRC_FILE = new File(WORK_DIR,"imgsrc.txt");
    final static File LOG_FILE = new File(WORK_DIR,"log.txt");
    final static String BASE_URL = "http://www.dotawiki.de";
    final static String HERO_BASE_URL = BASE_URL + "/index.php/";

    static PrintWriter log = null; 

    /**
     * @param args
     */
    public static void main ( String[] args ) throws Exception {
        LOG_FILE.delete();
        log = new PrintWriter(LOG_FILE); 

        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(SRC_FILE)); 
            String line = null;
            
            while ( (line = br.readLine()) != null ) {
                if ( line.indexOf('#') >= 0 ) {
                    handleLine(line);
                }
            }
                
        }
        finally {
            if ( br != null )
                try { br.close(); } catch ( Exception ex ) {};
            try { log.close(); } catch ( Exception ex ) {};
        }
    }

    private static void handleLine ( String line ) throws Exception {
        String[] toks = line.split("#");
        String heroName = toks[0];
        System.out.print(heroName + "...");
        List<String> htmlPage = getHtmlPage(heroName);
        System.out.println("ok");
        for ( int i = 1; i < toks.length; i++ ) {
            toks[i] = toks[i].replace(heroName,"");
            String imgFileName = mkImgFileName(toks[i]);
            System.out.print("    " + toks[i] + ")...");
            System.out.flush();
            if ( downloadImage(htmlPage,heroName,imgFileName) )
                System.out.println("ok");
            else {
                System.err.println("FAILED");
                log.println("could not get img for " + heroName + " ==> " + toks[i] + "(" + imgFileName + ")");
            }
        }
    }

    private static boolean downloadImage ( List<String> htmlPage, String heroName, String imgFileName ) throws Exception {
        // TODO Auto-generated method stub
        // <img alt="" src="/images/f/f0/Aphoticshield.gif" width="64" height="64" border="0" />
        // http://www.dotawiki.de/images/f/f0/Aphoticshield.gif
        String absUrl = null;
        Pattern pattern = Pattern.compile("<img\\salt=\".*\"\\ssrc=\"/images/\\w/\\w\\w*/" + imgFileName + "\\w*\\.\\w*");
        for ( String line : htmlPage ) {
            Matcher matcher = pattern.matcher(line);
            if ( matcher.find() ) {
                String group = matcher.group();
                String relUrl = group.substring(group.indexOf('/'));
                absUrl = BASE_URL + relUrl;
                break;
            }
        }
        if ( absUrl == null )
            return false;
        File localFile = mkLocalFile(heroName,absUrl);
        URL url = new URL(absUrl);
        URLConnection conn = url.openConnection();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(conn.getInputStream());
            bos = new BufferedOutputStream(new FileOutputStream(localFile));
            byte[] buf = new byte[1024];
            int got = 0;
            while ( (got = bis.read(buf)) > 0 )
                bos.write(buf,0,got);
        }
        finally {
            if ( bis != null )
                try { bis.close(); } catch ( Exception ex ) {};
            if ( bos != null )
                try { bos.close(); } catch ( Exception ex ) {};
        }
        
        
        return true;
    }

    private static File mkLocalFile ( String heroName, String absUrl ) {
        String heroPrefix = mkHeroPrefix(heroName);
        String fn = heroPrefix + absUrl.substring(absUrl.lastIndexOf('/') + 1);
        return new File(DOWNLOAD_DIR,fn.toLowerCase());
    }

    private static String mkHeroPrefix ( String heroName ) {
        int commaPos = heroName.indexOf(',');
        if ( commaPos > 0 )
            heroName = heroName.substring(0,commaPos);
        String res = "";
        int l = heroName.length();
        for ( int i = 0; i < l; i++ ) {
            char c = heroName.charAt(i);
            if ( Character.isLetter(c) ) {
                res += Character.toLowerCase(c);
            }
        }
        return res;
    }

    private static List<String> getHtmlPage ( String heroName ) throws Exception {
        // http://www.dotawiki.de/index.php/Zeus,_Lord_of_Olympus
        heroName = mkUrlFileName(heroName);
        URL url = new URL(HERO_BASE_URL + heroName);
        URLConnection conn = url.openConnection();
        ArrayList<String> res = new ArrayList<String>();
        BufferedReader br = null;
        try {
            br = new BufferedReader( new InputStreamReader(conn.getInputStream()));
            String line = null;
            while ( (line = br.readLine()) != null ) {
                res.add(line);
            }
        }
        finally {
            if ( br != null )
                try { br.close(); } catch ( Exception ex ) {};
        }
        return res;
    }

    private static String mkUrlFileName ( String heroName ) {
        String res = "";
        int l = heroName.length();
        for ( int i = 0; i < l; i++ ) {
            char c = heroName.charAt(i);
            if ( c == ' ' )
                res += '_';
            else
                res += c;
        }
        return res;
    }

    private static String mkImgFileName ( String skillName ) {
        String res = "";
        int l = skillName.length();
        for ( int i = 0; i < l; i++ ) {
            char c = skillName.charAt(i);
            if ( Character.isLetter(c) ) {
                res += '[';
                res += Character.toLowerCase(c);
                res += Character.toUpperCase(c);
                res += ']';
            }
            else if ( c == ' ' )
                res += "_?";
        }
        return res;
    }

}
